package org.janon.httpproxy.client.method;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.Socket;

import org.janon.httpproxy.ClientReadFromServer;
import org.janon.httpproxy.HttpModel;
import org.janon.httpproxy.HttpSession;
import org.janon.httpproxy.HttpUtil;
import org.janon.httpproxy.Log;
import org.janon.httpproxy.RequestLogStream;

public class ConnectDirectMethod
{
	private final static int BUFFER_SIZE = 96000;
	
	public static ClientReadFromServer doMethod(HttpModel httpModel, BufferedInputStream server_in, BufferedOutputStream server_out, BufferedInputStream client_in, BufferedOutputStream client_out, HttpSession session, RequestLogStream rls, String serverHost, int serverPort, Socket serverSocket) throws Exception
	{
		client_out.write((httpModel.getHttpType() + " 200 Connection established" + HttpUtil.CRLF).getBytes());
		Log.getInstance().writeRecordToFile(rls.getInputStream(), (httpModel.getHttpType() + " 200 Connection established"));
		client_out.write(HttpUtil.CRLF.getBytes());
		client_out.flush();
		Log.getInstance().writeRecordToFile(rls.getInputStream(), "");
		
		try
		{
			ConnectReadMethod crm = new ConnectReadMethod(server_in,client_out,serverSocket);
			int bytes_read = 0;
			byte[] buf = new byte[BUFFER_SIZE];
			while ((bytes_read = client_in.read(buf)) != -1)
			{
				if(serverSocket.isClosed())
				{
					break;
				}
				server_out.write(buf, 0, bytes_read);
				server_out.flush();
				Log.getInstance().writeRecordToFile(rls.getOutputStream(), new String(buf, 0, bytes_read));
			}
			crm.removeServerInputStreams();
		}
		catch (Exception e)
		{
		}
		return null;
	}
}
